package br.com.emmis.tercons.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import br.com.emmis.tercons.constants.Constants;
import br.com.emmis.tercons.model.Intention;

/**
 * Created by vaner on 22/01/2015.
 */
public class IntentionXMLUtil {

    private String mLine;
    private int mIntentionCount;
    private NodeList mNodes;
    private int mNextIntention;

    public IntentionXMLUtil(byte[] line) throws IOException, SAXException, ParserConfigurationException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new ByteArrayInputStream(line)));

        mNodes = doc.getElementsByTagName(Constants.XML_NODE_INTENCAO);
        mIntentionCount = mNodes.getLength();
        mNextIntention = 0;
    }

    public Intention getIntention(int position) {
        Intention intention = null;

        if(mIntentionCount > 0) {

            if(position >= mIntentionCount) {
                position = 0;
            }
            Element element = (Element) mNodes.item(position);

            String id = element.getElementsByTagName(Constants.XML_NODE_ID).item(0).getTextContent();
            String name = element.getElementsByTagName(Constants.XML_NODE_NOME).item(0).getTextContent();
            String prece = element.getElementsByTagName(Constants.XML_NODE_PRECE).item(0).getTextContent();
            String amem = element.getElementsByTagName(Constants.XML_NODE_AMEM).item(0).getTextContent();

            intention = new Intention();
            intention.setmId(Integer.parseInt(id));
            intention.setmName(name);
            intention.setmPrece(prece);
            intention.setmAmem(Integer.parseInt(amem));

            mNextIntention = position + 1;
        }
        return intention;
    }

    public Intention getRandomIntention() {
        Random random = new Random();
        mNextIntention = random.nextInt(mIntentionCount);
        return getIntention(mNextIntention);
    }

    public Intention getNextIntention() {
        return getIntention(mNextIntention);
    }

    public Intention getLastIntention() {
        return getIntention(0);
    }

    public int getIntentionCount() {
        return mIntentionCount;
    }
}
